<?php
namespace app\modules\merchant\services;

use app\common\services\BaseService;
use app\components\pagination\Pagination;
use app\models\Activity;
use app\modules\merchant\forms\activity\ActivityForm;

class ActivityService extends BaseService{

    /**
     * 搜索
     * @param $merchant_id
     * @param $page
     * @param $pagesize
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search($merchant_id,&$page,$pagesize){
        $query = Activity::find()->orderBy(['act_id'=>SORT_DESC]);

        if(!empty($merchant_id)){
            $query->andWhere(['merchant_id'=>$merchant_id]);
        }

        $page = new Pagination(['totalCount' => $query->count(), 'pageSize' => $pagesize]);
        $query->offset($page->getOffset());
        $query->limit($page->getLimit());

        return $query->all();
    }

    /**
     * 创建
     * @param ActivityForm $form
     * @return bool
     * @throws \Throwable
     */
    public static function create(ActivityForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = new Activity();
        $model->setAttributes($form->getAttributes(),false);
        return $model->insert() !== false;
    }

    /**
     * 更新
     * @param ActivityForm $form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function update(ActivityForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = Activity::findOne(['act_id'=>$form->act_id,'merchant_id'=>$form->merchant_id]);
        if(!$model){
            self::setError(\Yii::t("app","活动不存在"));
            return false;
        }
        $model->setAttributes($form->getAttributes(),false);
        return $model->update() !== false;
    }

    /**
     * 获取信息
     * @param $merchant_id
     * @param $id
     * @return Activity|null
     */
    public static function getInfoById($merchant_id,$id){
        return Activity::findOne(['act_id'=>$id,'merchant_id'=>$merchant_id]);
    }

    /**
     * 删除
     * @param $merchant_id
     * @param $id
     * @return int
     */
    public static function delete($merchant_id,$id){
        return Activity::deleteAll(['act_id'=>$id,'merchant_id'=>$merchant_id]);
    }
}